import Cookies from 'js-cookie'

// Cookie的Key
const TokenKey = 'Customer_Churn_Token'
const RefreshTokenKey = 'Customer_Churn_Refresh_Token'
const UserInfoKey = 'Customer_Churn_UserInfo'

// Cookie配置
const cookieOptions = {
  expires: 7, // 7天过期
  secure: false, // 开发环境设为false，生产环境应设为true
  sameSite: 'lax'
}

// 获取Token（优先从Cookie获取，fallback到localStorage）
export function getTokenFromCookie() {
  return Cookies.get(TokenKey) || localStorage.getItem(TokenKey)
}

// 设置Token到Cookie和localStorage
export function setTokenToCookie(token) {
  Cookies.set(TokenKey, token, cookieOptions)
  localStorage.setItem(TokenKey, token)
  
  // 设置过期时间
  const expireTime = new Date().getTime() + (7 * 24 * 60 * 60 * 1000) // 7天
  localStorage.setItem('Customer_Churn_Token_Expire', expireTime.toString())
}

// 移除Token
export function removeTokenFromCookie() {
  Cookies.remove(TokenKey)
  localStorage.removeItem(TokenKey)
  localStorage.removeItem('Customer_Churn_Token_Expire')
}

// 获取刷新令牌
export function getRefreshTokenFromCookie() {
  return Cookies.get(RefreshTokenKey) || localStorage.getItem(RefreshTokenKey)
}

// 设置刷新令牌
export function setRefreshTokenToCookie(token) {
  const refreshOptions = {
    ...cookieOptions,
    expires: 30 // 刷新令牌30天过期
  }
  Cookies.set(RefreshTokenKey, token, refreshOptions)
  localStorage.setItem(RefreshTokenKey, token)
}

// 移除刷新令牌
export function removeRefreshTokenFromCookie() {
  Cookies.remove(RefreshTokenKey)
  localStorage.removeItem(RefreshTokenKey)
}

// 获取用户信息
export function getUserInfoFromCookie() {
  const userInfo = Cookies.get(UserInfoKey) || localStorage.getItem(UserInfoKey)
  if (!userInfo) return null
  
  try {
    return JSON.parse(userInfo)
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return null
  }
}

// 设置用户信息
export function setUserInfoToCookie(userInfo) {
  const userInfoStr = JSON.stringify(userInfo)
  Cookies.set(UserInfoKey, userInfoStr, cookieOptions)
  localStorage.setItem(UserInfoKey, userInfoStr)
}

// 移除用户信息
export function removeUserInfoFromCookie() {
  Cookies.remove(UserInfoKey)
  localStorage.removeItem(UserInfoKey)
}

// 清除所有用户相关信息
export function clearAllUserData() {
  removeTokenFromCookie()
  removeRefreshTokenFromCookie()
  removeUserInfoFromCookie()
}

// 检查是否有有效的登录状态（Cookie或localStorage中有token）
export function hasValidLogin() {
  const token = getTokenFromCookie()
  if (!token) return false

  // 检查token是否过期
  const expireTime = localStorage.getItem('Customer_Churn_Token_Expire')
  if (expireTime) {
    const now = new Date().getTime()
    if (now > parseInt(expireTime)) {
      // token已过期，清除
      clearAllUserData()
      return false
    }
  }

  return true
}
